﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;

namespace MyBlog.Common
{
    public static class ExpressionMapper
    {
        public static Expression<Func<TTarget, bool>> MapExpression<TTarget, TSource>(this Expression<Func<TSource, bool>> keySelector)
        {
            return keySelector.MapExpression<TTarget, TSource, bool>();
        }

        public static Expression<Func<TTarget, TResult>> MapExpression<TTarget, TSource, TResult>(this Expression<Func<TSource, TResult>> keySelector)
        {
            //方式一
            //Mapper.Reset();
            //Mapper.CreateMap<TTarget, TSource>();
            Expression<Func<TTarget, TSource>> mapper = Extensions.CreateMapExpression<TTarget, TSource>(Mapper.Engine);
            Expression<Func<TTarget, TResult>> mappedSelector = x => keySelector.Compile()(mapper.Compile()((x)));
            return mappedSelector;

            //方式二
            //Mapper.CreateMap<TTarget, TSource>();
            //Func<TSource, TResult> match = keySelector.Compile();
            //Func<TTarget, TSource> mapper = Extensions.CreateMapExpression<TTarget, TSource>(Mapper.Engine).Compile();
            //Expression<Func<TTarget, TResult>> mappedSelector = x => match((mapper(x)));
            //return mappedSelector;
        }
    }
}
